# -*- coding: utf-8 -*-

import os
import sys
import timeit
from tool import plot
from func_moead import *



ins = ['ZDT1','ZDT2','ZDT3','ZDT4','ZDT6','DTLZ1','DTLZ2','DTLZ3','DTLZ4','DTLZ5','DTLZ6','DTLZ7',
'UF1','UF2','UF3','UF4','UF5','UF6','UF7','UF8','UF9','UF10']

# for k in range(len(ins)):
k = 7
dim = 14
nobj = 5

#Params(popsize,niche,dmethod,iteration,stop_nfeval,updateprob,updatenb,F,CR)
stop_nfeval = 330000/2
params = Params(330,50,'tc',2500,stop_nfeval,0.9,2,0.5,1)

mop = Problem(ins[k],dim,nobj)

# for j in range(num_run):
start = timeit.default_timer()
evalcounter = 0
subproblems, idealpoint = init_subproblem_classification(mop,params)
pf = np.array([subproblems[i].curpoint.value for i in range(params.popsize)])

itr = 0
while not terminate(evalcounter,params):

    #train SVM model
    classifier = train_randomforest_model(subproblems,params)
    # classifier = trainSVMmodel(subproblems, params)
    for i in range(params.popsize):
        updateneighbour = np.random.rand(1)[0] < params.updateprob
        newpoint = genetic_op(i,updateneighbour,mop,params,subproblems,'current')
        label = classifier.predict(newpoint.parameter.reshape(1,-1))
        r = np.random.rand(1)[0]

        if label == 1 or r <= 0.1:
            newpoint.value = mop.evaluate(newpoint.parameter)
            evalcounter = evalcounter + 1
            idealpoint = np.minimum(idealpoint,newpoint.value)
            update_vec(i,updateneighbour,newpoint,mop,params,subproblems,idealpoint)

            if terminate(evalcounter,params):
                break
    itr += 1
    print 'iteration: %d'%itr
stop = timeit.default_timer()

runtime_MOEAD = stop - start
print '%s running time: %f s'%(ins[k], runtime_MOEAD)

results_pf = np.array([subproblems[i].curpoint.value for i in range(params.popsize)])
# path = os.path.abspath(os.path.dirname(sys.argv[0]))
# truepf = np.loadtxt(path + "/PF/%s.dat"%mop.name)
# igd = calculateigd(truepf,results_pf)

np.savetxt('data/moead_svm_pf/%s_%dD.dat'%(ins[k],mop.nobj), results_pf, delimiter='\t')
plot(data=results_pf)

